<template>
	<div v-if="located === 'Filter'">不支持图片过滤</div>
	<template v-else>
		<div>{{ FieldItem?.TipsText }}</div>
		<el-upload
			v-bind="attrs"
			:disabled="!activate"
			:file-list="fileList"
			:before-upload="handleBeforeUpload"
			:on-remove="handleRemove"
			:on-preview="handlePreview"
			:on-exceed="handleExceed"
			:on-change="handleChange"
			:http-request="handleUploadRequest"
			class="upload"
		>
			<el-icon><Plus /></el-icon>
			<template #file="{ file }" v-if="FieldItem?.InputType === 'video' || FieldItem?.InputDefine?.fileType === '2'">
				<video :src="file.url" controls height="148" width="148"></video>
				<el-icon v-if="located !== 'Detail'" class="delete" :size="20" @click="handleRemove(file)"><DeleteFilled /></el-icon>
			</template>
			<template #file="{ file }" v-else-if="FieldItem?.InputDefine?.fileType === '1'">
				<div style="width: 100%; height: 100%; background-color: #409eff; display: flex; justify-content: center; align-items: center">
					<span style="color: #fff; cursor: pointer" @click="previewFile(file.url)">预览</span>
				</div>

				<el-icon v-if="located !== 'Detail'" class="delete" :size="20" @click="handleRemove(file)"><DeleteFilled /></el-icon>
			</template>
		</el-upload>
		<el-progress v-if="progress" :percentage="state.progressPercent" />
	</template>
	<el-dialog v-model="dialogVisible" destroy-on-close append-to-body>
		<img v-if="FieldItem?.InputType === 'el-img'" w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%" />
		<video v-else-if="FieldItem?.InputType === 'video' || FieldItem?.InputDefine?.fileType === '2'" :src="dialogImageUrl" controls></video>
	</el-dialog>

	<el-dialog
		@close="endCropper ? '' : fileList.pop()"
		width="1000px"
		v-model="showCropper"
		append-to-body
		title="需要将图片剪切至规范大小"
		:close-on-click-modal="false"
		destroy-on-close
	>
		<cropper
			:imgurl="imgurl"
			@cropperClone="cropperClone"
			:config="FieldItem?.pageType === 'page' ? FieldItem.attrs.cropperCfg : FieldItem!.InputDefine.cropperCfg"
		></cropper>
	</el-dialog>
</template>
<script lang="ts" setup>
import { ElMessage, UploadFile, UploadFiles, UploadRawFile, UploadRequestOptions } from 'element-plus';
import { DeleteFilled } from '@element-plus/icons-vue';
import { TabFieldType, TablePageType } from '../custom/DataStructs/commontype';
import FileIns from '/@/components/Linxyun/FileClient/FileClientApi/file_instance.js';
import useElement from './hooks/useElement';
import useTablePage from '../custom/TablePage/hooks/useTablePage';
import cropper from './cropper.vue';
const props = withDefaults(
	defineProps<{
		pageInfo?: TablePageType;
		filterIdx: number;
		located: string;
		modelValue: string;
		FieldItem: TabFieldType | null;
		pageData?: Record<string, any>;
		inputData?: Record<string, any>;
	}>(),
	{ located: 'table', filterIdx: -1, pageData: () => ({}), inputData: () => ({}), modelValue: '', FieldItem: null }
);
const { FieldItem, located } = toRefs(props);
const attrs: Record<string, any> = {
	listType: FieldItem.value!.InputDefine?.listType || 'picture-card',
	drag: FieldItem.value!.InputDefine?.drag || false,
	limit: FieldItem.value!.InputDefine?.limit || 1,
	action: '#',
	autoUpload: false,
};

const style = ref<Record<string, any>>({
	display: 'block',
});
const state = reactive<{
	activate: boolean;
	fileList: any[];
	deleteList: UploadFile[];
	dialogVisible: boolean;
	dialogImageUrl: string;
	videoArr: any[];
	fileClient: any;
	tempModelVal: any[];
	showCropper: boolean;
	endCropper: boolean;
	imgurl: string;
	progressPercent: number;
}>({
	activate: true,
	fileList: [],
	deleteList: [],
	dialogVisible: false,
	dialogImageUrl: '',
	videoArr: [],
	fileClient: null,
	tempModelVal: [],
	showCropper: false,
	endCropper: false, // 这个变量是判断有没有剪切图片，如果没有对图片进行剪切，关闭剪切弹窗时需要把选择的图片删除
	imgurl: '',
	progressPercent: 0,
});
const { activate, fileList, deleteList, dialogVisible, dialogImageUrl, videoArr, fileClient, tempModelVal, showCropper, endCropper, imgurl } =
	toRefs(state);

const progress = ref(false);

const fileConfig = ref();
if (localStorage.getItem('setting')) {
	fileConfig.value = JSON.parse(localStorage.getItem('setting') as string);
}

// 根据选择的上传样式来设置样式
if (attrs.listType === 'picture-card') {
	style.value = { padding: '50.5px 58px' };
} else if (['text', 'picture'].includes(attrs.listType)) {
	style.value = { padding: '52px 65px' };
}

const init = async () => {
	// 判断文件的类型来选择对应的上传类型
	if (FieldItem.value?.pageType === 'page') {
		FieldItem.value.InputDataType = 0;
		if (FieldItem.value.attrs.fileType === '0') {
			FieldItem.value.InputType = 'el-img';
		} else if (FieldItem.value.attrs.fileType === '2') {
			FieldItem.value.InputType = 'video';
		}
	}
	fileClient.value = await FileIns.instance(FieldItem.value!.InputDefine);
};
init();

const initFileList = () => {
	for (let i = 0; i < tempModelVal.value.length; i++) {
		console.log('---------------url', tempModelVal.value[i].url);
		if (!tempModelVal.value[i].url) {
			console.log('[Debug][File]The file is invalid, url undefined: ', tempModelVal.value[i]);
			continue;
		}
		let url = tempModelVal.value[i].url;
		if (!tempModelVal.value[i].url.startsWith('http')) {
			url = fileConfig.value.ImagUrl + tempModelVal.value[i].url;
		}
		const item = { uid: i, name: tempModelVal.value[i].name || tempModelVal.value[i].url, url: url, sourceUrl: tempModelVal.value[i].url };
		fileList.value.push(item);
	}
};
if (located.value === 'Edit') {
	initFileList();
} else if (located.value === 'Detail') {
	style.value.display = 'none';
}
watch(
	() => props.modelValue,
	(newVal: string) => {
		console.log('watch upload', newVal);
		const urlArr = newVal.split(';');
		for (let i = 0; i < urlArr.length; i++) {
			if (urlArr[i].indexOf(':=') !== -1) {
				const arr = urlArr[i].split(':=');
				tempModelVal.value.push({
					name: arr[0],
					url: arr[1],
				});
			} else {
				tempModelVal.value.push({
					name: urlArr[i],
					url: urlArr[i],
				});
			}
		}
		if (!newVal && located.value == 'Detail') {
			tempModelVal.value.push({
				name: '默认',
				url: 'https://element-plus.org/images/plant-1.png',
			});
		}
		initFileList();
	},
	{
		immediate: true,
	}
);
watch(
	() => props.modelValue,
	(newVal: string) => {
		console.log('watch newVal', newVal);
	}
);
// 文件上传前调用
const handleBeforeUpload = (file: UploadRawFile) => {
	console.log(file);
};
// 文件列表移除文件时调用
const handleRemove = (file: UploadFile) => {
	console.log('[Debug][File][handleRemove]file:', file);
	if (file.url) {
		deleteList.value.push(file);
		for (let i = 0; i < fileList.value.length; i++) {
			if (fileList.value[i].url === file.url) {
				fileList.value.splice(i, 1);
				break;
			}
		}
	}
};
// 点击文件列表中已上传的文件时调用
const handlePreview = (file: UploadFile) => {
	console.log('handlePreview', file);
	dialogVisible.value = true;
	dialogImageUrl.value = file.url!;
};
// 超出现在时调用
const handleExceed = () => {
	ElMessage.warning('超出了上传的最大限制！');
};
// 文件状态改变时的调用
const handleChange = (file: UploadFile, files: UploadFiles) => {
	if (FieldItem?.value?.InputDefine?.cropperCfg?.isCrop || (FieldItem.value?.pageType === 'page' && FieldItem.value.attrs.cropperCfg.isCrop)) {
		imgurl.value = file.url || '';
		showCropper.value = true;
	}
	fileList.value = files;
	getDuration();
};
// 文件上传
const handleUploadRequest = (option: UploadRequestOptions) => {
	console.log('handleUploadRequest option', option);
	const fileUrl = FileIns.instance().uploadFile();
	if (fileUrl === null) {
		onError();
		return;
	}
	fileList.value.push(fileUrl);
	onSuccess(fileUrl, fileList.value);
};
const onSuccess = (file: string, fileList: any[]) => {
	console.log('[Debug][File][Upload]success: ', file, fileList);
};
const onError = () => {
	ElMessage({ type: 'error', message: '上传图片失败！' });
	// throw new Error(err)
};
const getDuration = () => {
	nextTick(() => {
		setTimeout(() => {
			const video = document.getElementsByTagName('video');
			console.log('getDuration', video);
			videoArr.value = [];
			if (video.length) {
				video.forEach((item, i) => {
					videoArr.value.push({
						name: fileList.value[i].name,
						duration: item.duration,
					});
				});
			}
			console.log('vvvvvvvvvvvvvvvvvvvv', video, videoArr.value);
		}, 500);
	});
};
const cropperClone = (img) => {
	// console.log('imgimgimg', img)
	fileList.value[fileList.value.length - 1].size = img.size;
	fileList.value[fileList.value.length - 1].url = img.url;
	fileList.value[fileList.value.length - 1].raw = img.raw;
	console.log('this.fileListInner', fileList.value[fileList.value.length - 1]);
	endCropper.value = true;
	showCropper.value = false;
	nextTick(() => {
		endCropper.value = false;
	});
};
const uploadSubmit = async () => {
	console.log('[Debug][File][uploadSubmit]: ', fileList.value, deleteList.value);
	let item = {};
	const resList = [];
	let url = '';
	if (![0, 2].includes(fileConfig.value.FtpType)) {
		progress.value = true;
	}
	for (let i = 0; i < fileList.value.length; i++) {
		if (fileList.value[i].sourceUrl) {
			fileList.value[i].url = fileList.value[i].sourceUrl;
		}
		if (!fileList.value[i].raw) {
			// 已经上传了的文件，不再上传
			item = { name: fileList.value[i].name, url: fileList.value[i].url };
			resList.push(item);
			continue;
		}

		url = await state.fileClient.uploadContent(fileList.value[i].name, fileList.value[i].raw, state);
		console.log('urlurlurl', url);

		if (url === null) {
			console.error('[Error][File]upload file fail: ', fileList.value[i]);
			continue;
		}

		item = { name: fileList.value[i].name, url: url };
		resList.push(item);
	}

	for (let i = 0; i < deleteList.value.length; i++) {
		if (fileConfig.value.FtpType === 3) {
			state.fileClient.deleteFile(deleteList.value[i]);
		} else {
			state.fileClient.deleteFile(deleteList.value[i].url);
		}
	}
	return resList;
};
const { handleDisable } = useElement(located, FieldItem.value!, fileList, props);
watch(
	() => fileList.value,
	() => {
		console.log('watch fileList', fileList.value.length);

		if (fileList.value.length >= attrs.limit) {
			// activate.value = true;
			style.value.display = 'none';
		} else {
			style.value.display = 'block';
		}
	},
	{
		deep: true,
	}
);
handleDisable(activate);
const { previewFile } = useTablePage();
defineExpose({
	uploadSubmit,
	videoArr,
});
</script>
<style lang="scss" scoped>
:deep(.el-upload-dragger) {
	padding: v-bind('style.padding');
}
:deep(.el-upload.is-drag) {
	display: v-bind('style.display');
}
.delete {
	position: absolute;
	right: 5px;
	top: 5px;
	cursor: pointer;
}
// .upload:deep(.el-upload .el-upload--picture-card .is-drag .el-list-move) {
// 	display: v-bind('displayStyle');
// }
</style>
